#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/22
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

import os
from math import ceil
from flask import json, session
from project.define import AxiosMessage


class Messager(AxiosMessage):
    """
    消息管理器
    """
    def __init__(self) -> None:
        super().__init__()
        self.carpark_log_path = "logs/carpark"
        self.camera_log_path = "logs/camera"
        
    def camera_logs_data(self, page):
        """
        日志预览数据
        """
        logs = [i for i in os.listdir(self.camera_log_path) if not i.startswith(".")]
        log_file = session.get("CameraLog")
        if not log_file:
            log_file = logs[0]
        with open(f"{self.camera_log_path}/{log_file}", mode="r", encoding="utf8") as f:
            log_info = f.readlines()
        log_info.reverse()
        # 获取页数
        pages = ceil(len(log_info) / 100)
        page_iters = list(range(pages+1))
        page_iters.remove(0)
        if page == 1:
            page_info = log_info[:100]
            if pages <= 1:
                page_iters = [1,]
        else:
            start = page * 100
            end = (page+1) * 100
            page_info = log_info[start:end]
        return {'log_file': log_file, 'logs': logs, 'page_info': page_info, 'pages': page_iters, 'current_page': page}

    def carpark_logs_data(self, page):
        """
        日志预览数据
        """
        log_file = session.get("CarParkLog")
        if not log_file:
            log_file = "app.log"
        logs = [i for i in os.listdir(self.carpark_log_path) if not i.startswith(".")]
        with open(f"{self.carpark_log_path}/{log_file}", mode="r", encoding="utf8") as f:
            log_info = f.readlines()
        log_info.reverse()
        # 获取页数
        pages = ceil(len(log_info) / 100)
        page_iters = list(range(pages+1))
        page_iters.remove(0)
        if page == 1:
            page_info = log_info[:100]
            if pages <= 1:
                page_iters = [1,]
        else:
            start = page * 100
            end = (page+1) * 100
            page_info = log_info[start:end]
        return {'log_file': log_file, 'logs': logs, 'page_info': page_info, 'pages': page_iters, 'current_page': page}
